# -*- coding: utf-8 -*-
"""
月日历图片生成器
"""

import calendar
import datetime
from PIL import Image, ImageDraw, ImageFont
import io
import base64
import os
from config import width, height, is_all_black

def generate_monthly_calendar(year=None, month=None):
    """
    生成月日历图片
    :param year: 年份，默认为当前年份
    :param month: 月份，默认为当前月份
    :return: 生成的图片对象
    """
    # 如果未指定年月，使用当前日期
    if year is None or month is None:
        now = datetime.datetime.now()
        year = now.year
        month = now.month
    
    # 创建日历对象
    cal = calendar.monthcalendar(year, month)
    
    # 创建图片
    # 白色背景
    bg_color = (255, 255, 255)
    img = Image.new('RGB', (width, height), color=bg_color)
    draw = ImageDraw.Draw(img)
    
    # 尝试加载字体，如果失败则使用默认字体
    try:
        # 尝试加载中文字体
        font_path = "C:\\Windows\\Fonts\\simhei.ttf"  # 黑体
        if not os.path.exists(font_path):
            font_path = "C:\\Windows\\Fonts\\simsun.ttc"  # 宋体
        
        # 设置字体大小
        title_font_size = 48
        weekday_font_size = 36
        day_font_size = 30
        
        title_font = ImageFont.truetype(font_path, title_font_size)
        weekday_font = ImageFont.truetype(font_path, weekday_font_size)
        day_font = ImageFont.truetype(font_path, day_font_size)
    except IOError:
        # 使用默认字体
        title_font = ImageFont.load_default()
        weekday_font = ImageFont.load_default()
        day_font = ImageFont.load_default()
    
    # 绘制月份标题
    month_names = ["一月", "二月", "三月", "四月", "五月", "六月", 
                  "七月", "八月", "九月", "十月", "十一月", "十二月"]
    title_text = f"{year}年 {month_names[month-1]}"
    # 使用textbbox获取文本边界框
    left, top, right, bottom = draw.textbbox((0, 0), title_text, font=title_font)
    title_width = right - left
    title_height = bottom - top
    # 标题文字颜色始终为黑色
    text_color = (0, 0, 0)
    draw.text(((width - title_width) // 2, 20), title_text, font=title_font, fill=text_color)
    
    # 绘制星期标题
    weekdays = ["一", "二", "三", "四", "五", "六", "日"]
    weekday_width = width // 7
    for i, day in enumerate(weekdays):
        # 使用textbbox获取文本边界框
        left, top, right, bottom = draw.textbbox((0, 0), day, font=weekday_font)
        day_width = right - left
        x = i * weekday_width + (weekday_width - day_width) // 2
        # 根据is_all_black参数决定颜色
        if i >= 5 and not is_all_black:
            color = (255, 0, 0)  # 如果不是全黑模式，周六周日为红色
        else:
            color = (0, 0, 0)  # 否则全部为黑色
        draw.text((x, 100), day, font=weekday_font, fill=color)
    
    # 计算日历网格参数
    grid_top = 150
    grid_height = height - grid_top - 20
    row_height = grid_height // 6  # 日历最多6行
    
    # 绘制日历
    for row_idx, week in enumerate(cal):
        for col_idx, day in enumerate(week):
            if day != 0:
                day_text = str(day)
                # 使用textbbox获取文本边界框
                left, top, right, bottom = draw.textbbox((0, 0), day_text, font=day_font)
                day_width = right - left
                day_height = bottom - top
                x = col_idx * weekday_width + (weekday_width - day_width) // 2
                y = grid_top + row_idx * row_height + (row_height - day_height) // 2
                
                # 根据is_all_black参数决定颜色
                if col_idx >= 5 and not is_all_black:
                    color = (255, 0, 0)  # 如果不是全黑模式，周六周日为红色
                else:
                    color = (0, 0, 0)  # 否则全部为黑色
                draw.text((x, y), day_text, font=day_font, fill=color)
    
    return img

def save_calendar_image(img, output_path):
    """
    保存日历图片
    :param img: 图片对象
    :param output_path: 输出路径
    """
    img.save(output_path)
    print(f"日历图片已保存至: {output_path}")

def get_calendar_base64(img):
    """
    获取日历图片的base64编码
    :param img: 图片对象
    :return: base64编码的图片字符串
    """
    buffered = io.BytesIO()
    img.save(buffered, format="PNG")
    return f"data:image/png;base64,{base64.b64encode(buffered.getvalue()).decode('utf-8')}"

def generate_small_calendar_with_padding(year=None, month=None, scale_factor=4):
    """
    生成月日历图片，然后缩小并补白到原始尺寸
    :param year: 年份，默认为当前年份
    :param month: 月份，默认为当前月份
    :param scale_factor: 缩小比例，默认为4（即缩小到原来的1/4）
    :param is_all_black: 是否所有文字都为黑色（没有红色），默认为True
    :return: 补白后的图片对象
    """
    original_width=width
    original_height=height
    # 先生成原始尺寸的日历图片
    original_calendar = generate_monthly_calendar(year, month)
    
    # 计算缩小后的尺寸
    small_width = original_width // scale_factor
    small_height = original_height // scale_factor
    
    # 缩小图片
    small_calendar = original_calendar.resize((small_width, small_height), Image.LANCZOS)
    
    # 创建原始尺寸的白色背景图片
    padded_img = Image.new('RGB', (original_width, original_height), color=(255, 255, 255))
    
    # 计算居中位置
    paste_x = (original_width - small_width) // 2
    paste_y = (original_height - small_height) // 2
    
    # 将缩小的日历图片粘贴到白色背景上
    padded_img.paste(small_calendar, (paste_x, paste_y))
    
    return padded_img

if __name__ == "__main__":
    # 是否生成缩小的日历图片并补白
    use_small_calendar = True
    scale_factor = 4  # 缩小比例，默认为4（即缩小到原来的1/4）
    
    if use_small_calendar:
        # 生成缩小的当月日历并补白
        print(f"生成缩小的日历图片（缩小比例：1/{scale_factor}）并补白...")
        calendar_img = generate_small_calendar_with_padding(scale_factor=scale_factor)
        save_calendar_image(calendar_img, "monthly_calendar_small_padded.png")
        
        # 同时保存一个未补白的小尺寸图片作为对比
        # 先生成原始尺寸的日历图片
        original_calendar = generate_monthly_calendar()
        # 然后缩小到指定比例
        small_width = 960 // scale_factor
        small_height = 640 // scale_factor
        small_calendar = original_calendar.resize((small_width, small_height), Image.LANCZOS)
        save_calendar_image(small_calendar, "monthly_calendar_small.png")
    else:
        # 生成原始尺寸的当月日历
        calendar_img = generate_monthly_calendar()
        save_calendar_image(calendar_img, "monthly_calendar.png")